import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yfree/YFree.dart';

enum MyNumPickerInputMode { Input, Alert }

class MyNumPicker extends StatefulWidget {
  MyNumPicker({
    Key? key,
    required this.value,
    required this.max,
    required this.onChange,
    this.onCreate,
    this.mode = MyNumPickerInputMode.Alert,
  }) : super(key: key);

  int value;
  final int max;
  final Function(int value) onChange;
  Function(MyNumPickerController controller)? onCreate;
  MyNumPickerInputMode mode;

  @override
  _MyNumPickerState createState() => _MyNumPickerState();
}

class _MyNumPickerState extends State<MyNumPicker> {
  final controller_count = TextEditingController();
  final focusNode_count = FocusNode();

  @override
  void initState() {
    super.initState();
    controller_count.text = widget.value.toString();
    focusNode_count.addListener(() {
      if (!focusNode_count.hasFocus) {
        if (controller_count.text.isEmpty || int.parse(controller_count.text) <= 0) controller_count.text = "1";
        if (int.parse(controller_count.text) > widget.max) controller_count.text = widget.max.toString();
        widget.value = int.parse(controller_count.text);
        widget.onChange.call(widget.value);
        setState(() {});
      }
    });
    widget.onCreate?.call(MyNumPickerController(this));
  }

  @override
  void dispose() {
    focusNode_count.dispose();
    controller_count.dispose();
    super.dispose();
  }

  Widget getInputWidget() {
    switch (widget.mode) {
      case MyNumPickerInputMode.Input:
        return Container(
          margin: EdgeInsets.fromLTRB(2, 0, 2, 0),
          child: TextFormField(
            focusNode: focusNode_count,
            textAlign: TextAlign.center,
            controller: controller_count,
            decoration: InputDecoration(border: InputBorder.none),
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(6)],
            style: TextStyle(fontSize: 14),
          ),
        );
      case MyNumPickerInputMode.Alert:
        final textController = TextEditingController(text: widget.value.toString());
        return YButton(
          child: Text(widget.value.toString()),
          onTap: () {
            yShowDialog(
              alertBuilder: (pageContext, dialogContext) {
                return AlertDialog(
                  title: Text("请输入数量"),
                  content: TextFormField(
                    controller: textController,
                    decoration: InputDecoration(hintText: "请输入数量"),
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(4)],
                  ),
                  actions: [
                    YButton(
                      child: Text("取消"),
                      onTap: () => yDismissDialog(dialogContext),
                    ),
                    YButton(
                      child: Text("确定"),
                      onTap: () {
                        yDismissDialog(dialogContext);
                        if (textController.text.isEmpty || int.parse(textController.text) <= 0) textController.text = "1";
                        if (int.parse(textController.text) > widget.max) textController.text = widget.max.toString();
                        widget.value = int.parse(textController.text);
                        widget.onChange.call(widget.value);
                        setState(() {});
                      },
                    ),
                  ],
                );
              },
            );
          },
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    var jianEnable = controller_count.text != "" && controller_count.text != "0" && controller_count.text != "1";
    var jiaEnable = controller_count.text != "" && controller_count.text != "0" && int.parse(controller_count.text) < widget.max;
    return Container(
      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: Colors.grey.shade300, width: 1), borderRadius: BorderRadius.circular(5)),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          YButton(
            width: 25,
            height: 25,
            child: Icon(Icons.remove_rounded, color: jianEnable ? Colors.black : Colors.grey.shade300, size: 20),
            enable: jianEnable,
            onTap: () {
              var result = int.parse(controller_count.text.isEmpty ? "0" : controller_count.text);
              if (result - 1 > 0) {
                widget.value = result - 1;
                widget.onChange.call(widget.value);
                controller_count.text = widget.value.toString();
                setState(() {});
              }
            },
          ),
          Container(width: 1, height: 25, color: Colors.grey.shade300),
          Container(
            height: 25,
            width: 50,
            child: getInputWidget(),
          ),
          Container(width: 1, height: 25, color: Colors.grey.shade300),
          YButton(
            width: 25,
            height: 25,
            child: Icon(Icons.add_rounded, color: jiaEnable ? Colors.black : Colors.grey.shade300, size: 20),
            enable: jiaEnable,
            onTap: () {
              var result = int.parse(controller_count.text.isEmpty ? "0" : controller_count.text);
              if (result + 1 <= widget.max) {
                widget.value = result + 1;
                widget.onChange.call(widget.value);
                controller_count.text = widget.value.toString();
                setState(() {});
              }
            },
          ),
        ],
      ),
    );
  }
}

class MyNumPickerController {
  MyNumPickerController(this._state);

  _MyNumPickerState _state;

  void setValue(int value) {
    _state.widget.value = value;
    _state.widget.onChange.call(_state.widget.value);
    _state.controller_count.text = _state.widget.value.toString();
    _state.setState(() {});
  }
}
